<template>
  <el-card class="calendar-event-card" v-show="visible">
    <div slot="header" class="clearfix">
      <span>{{ title }}</span>
      <div class="header-button">
        <template v-if="model.id && ownerUser.code === user.code">
          <svg-icon icon-class="star_on" class="on" title="已关注，点击取消关注" @click.native="doMark" v-if="model.markcolor === '9'"></svg-icon>
          <svg-icon icon-class="star" title="未关注，点击关注" @click.native="doMark" v-else></svg-icon>
        </template>
        <i class="el-icon-delete" title="删除" v-if="model.id && !readonly" @click="doDelete"></i>
        <i class="el-icon-close" title="关闭" @click="doCancelEdit"></i>
      </div>
    </div>
    <el-form class="tl-form tl-card-form" ref="form" size="small" :model="model" :rules="rules" label-width="1px" :disabled="disableEditSubmit || readonly">
      <el-row>
        <el-col :span="24">
          <el-form-item label="" prop="name" :rules="rules.validateRequire">
            <el-input v-model="model.name" maxlength="50" show-word-limit class="input-with-select">
              <el-select v-model="model.scheduletype" filterable slot="prepend">
                <el-option v-for="item in codeModel.scheduletypeList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1">
          <i class="el-icon-date" title="日期"></i>
        </el-col>
        <el-col :span="11">
          <el-form-item label="" prop="begintime" :rules="rules.validateRequire" style="padding-left:5px">
            <el-date-picker v-model="model.begintime" type="datetime" placeholder="开始时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          -
        </el-col>
        <el-col :span="11">
          <el-form-item label="" prop="endtime" :rules="rules.validateRequire">
            <el-date-picker v-model="model.endtime" type="datetime" placeholder="结束时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1">
          <i class="el-icon-collection" title="标签"></i>
        </el-col>
        <el-col :span="23">
          <el-form-item label="" prop="tags" style="padding-left:5px">
            <div class="tag-container">
              <el-tag :key="tag" v-for="tag in tagList" :closable="!disableEditSubmit && !readonly" :disable-transitions="false" @close="handleClose(tag)">
                {{ tag }}
              </el-tag>
              <el-input class="input-new-tag" maxlength="10" placeholder="最多10个字" v-if="inputVisible" style="width:100px;" v-model="inputValue" ref="saveTagInput" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"> </el-input>
              <el-button v-else circle @click="showInput" icon="el-icon-plus" size="mini"></el-button>
              <tl-help>
                可自定义设置标签，便于搜索和提醒，字数最多不超过10个。如：带电脑、需要录音等。
              </tl-help>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="text-align:right;overflow:hidden;">
      <span class="owner-tip" v-if="isAdd">日程所属人：{{ ownerUser.name }}</span>
      <el-button size="mini" icon="el-icon-document" @click="openMeetDetail" v-if="model.sourcetype === 'MeetManage' && isAttendUser">会议详情</el-button>
      <el-button type="default" icon="el-icon-date" v-if="model.sourcetype === 'workTask' && !ownerUser.isView && model.id" size="mini" @click="openPeriodList">查看周期日程</el-button>
      <el-button size="mini" icon="el-icon-more" @click="openMore" v-if="!ownerUser.isView || !readonly">更多选项</el-button>
      <el-button type="primary" icon="el-icon-finished" @click="checkConflict" :loading="saveLoading" size="mini" v-if="!disableEditSubmit && !readonly">保存</el-button>
    </div>
    <period-list ref="periodList" :ownerUser="ownerUser" :readonly="readonly" @closeAll="closeAll" @refresh="transRefresh"></period-list>
    <conflict-list ref="conflictList" :dataList="conflictList"></conflict-list>
    <meet-edit ref="meetEdit"></meet-edit>
  </el-card>
</template>

<script>
/** mixins */
import { mixin_edit } from "@tapui/mixins/mixin_edit"
/** 子组件 */
import periodList from "./periodList"
import conflictList from "./conflictList"
import meetEdit from "@/views/meet/meetManage/edit"
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from "@tapui/utils/http"
import { formatDate } from "@tapui/utils/date"
import { queryDataCode } from "@tapui/api/dataCode"
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: { periodList, conflictList, meetEdit },
  data() {
    return {
      moduleTitle: "工作日程",
      urlPrefix: "/work/schedule/",
      url: {
        // 额外的url
        add: "/work/schedule/saveCalendar",
        edit: "/work/schedule/saveCalendar",
        queryRemind: "/base/remindConfig/list",
        delete: "/work/schedule/delete",
        mark: "/base/operateRecord/operateState",
        queryConflict: "/base/permissionManage/checkTimeConflict",
        queryUser: "/base/permissionManage/queryList",
        judgeIsAttendUser: "/base/permissionManage/judgeIsAttendUser"
      },
      // 提醒相关
      remindId: -1,
      remindList: [],
      remindTypeList: [],
      noticeTypeList: [],
      remindUnitTypeList: [],
      // 下面仨是标签相关
      inputVisible: false,
      inputValue: "",
      tagList: [],
      // 多人会议
      users: {
        usernames: "",
        usercodes: "",
        deptnames: "",
        deptcodes: "",
        teamids: "",
        teamnames: "",
        roleids: "",
        rolenames: "",
        sharecodes: "",
        sharenames: ""
      },
      // 冲突记录
      conflictList: [],
      conflictVisible: false,
      isAttendUser: false
    }
  },
  props: {
    dateInfo: {
      type: Object,
      default: function() {
        return null
      }
    },
    // 默认日程所属人
    ownerUser: {
      type: Object,
      default: function() {
        return {
          code: "",
          name: ""
        }
      }
    }
  },
  computed: {
    readonly() {
      return !this.isAdd && this.user.code !== this.model.handleusercode
    }
  },
  methods: {
    loaded() {
      // 页面加载完毕执行
      if (this.model.sourcetype) {
        this.judgeIsAttendUser()
      }
      this.tagList = []
      if (!this.isAdd) {
        if (this.model.tags !== null && this.model.tags.length > 0) {
          this.tagList = this.model.tags.split(",")
        }
        this.queryRemind()
        this.queryUser()
        if (this.readonly || this.disableEditSubmit) {
          this.title = "查看" + this.moduleTitle
        }
      } else {
        if (this.user.code === this.ownerUser.code) {
          this.users.usernames = this.ownerUser.name
          this.users.usercodes = this.ownerUser.code
        } else {
          this.users.sharenames = this.ownerUser.name
          this.users.sharecodes = this.ownerUser.code
        }
        this.$set(this.model, "scheduletype", "work")
        if (this.dateInfo !== null) {
          this.assignDefaultTime()
        }
        this.remindList = [
          {
            id: 0,
            remindtype: "1",
            noticetype: "app",
            unit: "1",
            value: 2,
            timeValue: "09:00:00"
          }
        ]
        let that = this
        setTimeout(function() {
          that.$refs.form.clearValidate()
        }, 100)
      }
    },
    // 新增时，根据日历选择的时间进行赋值
    assignDefaultTime() {
      let dateStr = this.dateInfo.dateStr
      if (dateStr.length === 10) {
        // 在月视图点击
        this.$set(this.model, "begintime", dateStr + " 09:00:00")
        this.$set(this.model, "endtime", dateStr + " 10:00:00")
      } else {
        // 增加一小时
        this.$set(this.model, "begintime", formatDate(this.dateInfo.date, "yyyy-MM-dd HH:mm:ss"))
        this.$set(this.model, "endtime", formatDate(new Date(this.dateInfo.date.getTime() + 60 * 60 * 1000), "yyyy-MM-dd HH:mm:ss"))
      }
    },
    beforeSubmit() {
      this.model.tags = this.tagList.join(",")
      if (this.model.begintime > this.model.endtime) {
        this.$tap.message("开始时间不能小于结束时间", "error")
        return false
      }
      let remindList = []
      this.remindList.forEach((remind, index) => {
        remindList.push({
          id: remind.id,
          remindtype: remind.remindtype,
          unit: remind.unit,
          value: remind.remindtype === "1" ? remind.value : remind.timeValue,
          noticetype: remind.noticetype,
          sortcode: index
        })
      })
      this.model.remindList = remindList
      this.model.selectUsers = this.users
      return true
    },
    // 更改日程开始时间后，若结束时间相差不到一小时，则延后结束时间
    changeBeginTime() {
      if (this.model.begintimeTime === null) {
        return
      }
      let beginArr = this.model.begintimeTime.split(":")
      if (beginArr[0] === "23" || beginArr[0] === "24") {
        return
      }
      let endArr = this.model.endtimeTime.split(":")
      let begin = parseInt(beginArr[0]) * 60 + parseInt(beginArr[1])
      let end = parseInt(endArr[0]) * 60 + parseInt(endArr[1])
      if (end - begin <= 60) {
        let hour = (parseInt(beginArr[0]) + 1).toString()
        if (hour.length === 1) {
          hour = "0" + hour
        }
        this.model.endtimeTime = `${hour}:${beginArr[1]}`
      }
    },
    queryRemind() {
      getAction(this.url.queryRemind, { qry_sourcetype: "workSchedule", qry_sourceid: this.model.id, sidx: "sortcode", sord: "asc" }).then(res => {
        if (res.success) {
          this.remindList = []
          res.result.dataList.forEach(m => {
            this.remindList.push({
              id: m.id,
              remindtype: m.remindtype,
              noticetype: m.noticetype,
              unit: m.unit,
              value: m.remindtype === "1" ? m.value : "1",
              timeValue: m.remindtype === "2" ? m.value : "09:00:00"
            })
          })
        }
      })
    },
    // 查询已有人员
    queryUser() {
      getAction(this.url.queryUser, { qry_sourcetype: "workSchedule", qry_sourceid: this.model.id, qry_sourceflag: "owner" }).then(res => {
        if (res.success) {
          for (let key of Object.keys(this.users)) {
            this.users[key] = ""
          }
          res.result.forEach(m => {
            if (m.sharetype === "5") {
              this.users.usernames = m.shareobjectsdesc
              this.users.usercodes = m.shareobjects
            } else if (m.sharetype === "1") {
              this.users.deptnames = m.shareobjectsdesc
              this.users.deptcodes = m.shareobjects
            } else if (m.sharetype === "3") {
              this.users.rolenames = m.shareobjectsdesc
              this.users.roleids = m.shareobjects
            } else if (m.sharetype === "2") {
              this.users.teamnames = m.shareobjectsdesc
              this.users.teamids = m.shareobjects
            } else if (m.sharetype === "6") {
              this.users.sharenames = m.shareobjectsdesc
              this.users.sharecodes = m.shareobjects
            }
          })
        }
      })
    },
    // 标签相关
    handleClose(tag) {
      this.tagList.splice(this.tagList.indexOf(tag), 1)
    },
    // 标签相关
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 标签相关
    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.tagList.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ""
    },
    doDelete() {
      this.$tap
        .confirm("确定删除数据吗？")
        .then(_ => {
          deleteAction(this.url.delete, { ids: this.model.id }).then(res => {
            if (res.success) {
              this.$tap.message(res.message, "success")
              this.visible = false
              this.$emit("refresh")
            } else {
              this.$tap.alert(res.message, "warning")
            }
          })
        })
        .catch(_ => {})
    },
    // 关注
    doMark() {
      postAction(this.url.mark, { sourcetype: "workSchedule", sourceid: this.model.id, operatetype: "attention", operateresult: "9" }).then(res => {
        if (res.success) {
          this.queryData(this.id)
          this.$emit("refresh")
        }
      })
    },
    // 更多选项
    openMore() {
      this.visible = false
      this.model.tags = this.tagList.join(",")
      this.$emit("more", this.model)
    },
    // 会议详情
    openMeetDetail() {
      if (this.model.sourcetype !== "MeetManage") {
        return
      }
      this.visible = false
      this.$refs.meetEdit.id = parseInt(this.model.sourceid)
      this.$refs.meetEdit.isAdd = false
      this.$refs.meetEdit.visible = true
      this.$refs.meetEdit.disableEditSubmit = true
    },
    transRefresh() {
      this.open()
      this.$emit("refresh")
    },
    closeAll() {
      this.isAttendUser = false
      this.visible = false
      this.$emit("refresh")
    },
    openPeriodList() {
      this.$refs.periodList.filtersInfo = {
        qry_sourcetype: "workTask",
        qry_sourceid: this.model.sourceid,
        qry_sourceapp: "work"
      }
      this.$refs.periodList.visible = true
    },
    checkConflict() {
      this.saveLoading = true
      let param = {
        ...this.users,
        begintime: this.model.begintime,
        endtime: this.model.endtime
      }
      if (!this.isAdd) {
        param.id = this.model.id
      }
      getAction(this.url.queryConflict, param)
        .then(res => {
          if (res.success) {
            this.conflictList = res.result
            if (res.result.length > 0) {
              this.$confirm("所选日程接收人中存在时间冲突，是否继续保存？", "提示", {
                confirmButtonText: "查看冲突",
                cancelButtonText: "忽略冲突继续保存",
                type: "warning"
              })
                .then(_ => {
                  // 查看冲突
                  this.$refs.conflictList.visible = true
                  this.saveLoading = false
                })
                .catch(_ => {
                  this.saveLoading = false
                  // 忽略继续保存
                  this.doSubmitEdit()
                })
            } else {
              this.saveLoading = false
              // 没有冲突
              this.doSubmitEdit()
            }
          } else {
            this.saveLoading = false
            // 调用接口出错了
            this.conflictList = []
            this.doSubmitEdit()
          }
        })
        .catch(_ => {
          this.saveLoading = false
          // 调用接口出错了
          this.conflictList = []
          this.doSubmitEdit()
        })
    },
    /** 查询用户是否为该会议的参会人员 */
    judgeIsAttendUser() {
      getAction(this.url.judgeIsAttendUser, { qry_sourcetype: "MeetManage", qry_sourceid: this.model.sourceid }).then(res => {
        if (res.success) {
          this.isAttendUser = res.result.isAttendUser
        } else {
          this.isAttendUser = false
        }
      }).catch(err => {
          this.isAttendUser = false
      })
    }
  },
  created() {}
}
</script>
<style scoped lang="scss">
.tag-container {
  .el-tag {
    margin-right: 5px;
    margin-bottom: 5px;
  }
}
.color-block {
  display: inline-block;
  height: 15px;
  width: 15px;
}
.input-with-select {
  .el-select {
    width: 100px;
  }
}
.header-button {
  float: right;
  i,
  svg {
    cursor: pointer;
    &.on {
      color: #f56c6c;
    }
  }
}
.owner-tip {
  float: left;
  line-height: 29px;
  color: #888;
  font-size: 13px;
}
</style>
<style lang="scss">
.calendar-event-card {
  .el-card__header {
    padding: 10px 10px 6px;
  }
}
.tl-card-form {
  .el-col-1 {
    line-height: 32px;
    height: 32px;
    text-align: center;
  }
}
</style>
